package middleware

import (
	"github.com/casbin/casbin/v2"
	"github.com/gin-gonic/gin"
	"net/http"
	"smart-sensor-cloud/pkg/auth"
	"smart-sensor-cloud/pkg/util"
	"strconv"
)

func CasbinMiddleware(enabled bool, enforcer *casbin.SyncedEnforcer, skippers ...Skipper) gin.HandlerFunc {
	if !enabled {
		return EmptyMiddleware()
	}

	return func(ctx *gin.Context) {
		ctx.Set(auth.SyncedEnforcerKey, enforcer)
		if SkipHandler(ctx, skippers...) {
			ctx.Next()
			return
		}

		path := ctx.Request.URL.Path
		method := ctx.Request.Method

		token := GetToken(ctx)
		jwtGenerator := ctx.MustGet(JWTGeneratorKey).(*auth.JWTGenerator)
		claims, err := jwtGenerator.ParseTokenToClaims(token)
		if err != nil {
			ctx.JSON(http.StatusOK, &util.Error{
				Code:    http.StatusUnauthorized,
				Message: "非法的Token, 无法进行访问",
			})
			ctx.Abort()
			return
		}

		if b, err := enforcer.Enforce(strconv.Itoa(claims.UserID), path, method); err != nil {
			ctx.JSON(http.StatusOK, &util.Error{
				Code:    http.StatusInternalServerError,
				Message: err.Error(),
			})
			ctx.Abort()
			return
		} else if !b {
			ctx.JSON(http.StatusOK, util.NewUnauthorizedRequestError("无访问权限"))
			ctx.Abort()
			return
		}

		ctx.Next()
	}
}
